#include "MemoryStream.h"
#include <iostream>
#include <cassert>

namespace streamdb {

MemoryStream::~MemoryStream(){
    msgs.clear();
}

Status MemoryStream::append(const OrderedMessage & obj) {
    if(!obj.isNull()){
        std::cout << "MemoryStream save the msg:" << obj.toString() << std::endl;
        msgs.push_back(obj);
    }
    else{
        std::cout << "message is null, don't save it:" << obj.toString() << std::endl;
    }
    return Status::OK();
}
uint64_t MemoryStream::getSize() const  {
    return msgs.size();
}

MemoryStream::iterator::iterator(const std::vector<OrderedMessage>::iterator & cur, const std::vector<OrderedMessage>::iterator & end) 
: cur(cur), end(end) {
}
MemoryStream::iterator::~iterator() {
}

bool MemoryStream::iterator::hasNext() const {
    return cur ==  end;
}
OrderedMessage & MemoryStream::iterator::next() {
    auto & ret = *cur;
    ++cur;
    return ret;
}

std::shared_ptr<SequenceStream<OrderedMessage>::IteratorType> 
MemoryStream::advance(int64_t offset) {
    if(offset < getSize()){
        std::vector<OrderedMessage>::iterator iter = msgs.begin();
        std::advance(iter, offset);
        return std::make_shared<iterator>(iter, msgs.end());
    }
    return std::make_shared<iterator>(msgs.end(), msgs.end());
}
std::shared_ptr<SequenceStream<OrderedMessage>::IteratorType> 
MemoryStream::begin() {
    return std::make_shared<iterator>(msgs.begin(), msgs.end());
}





}//namespace streamdb
